﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Volo.Abp.Domain.Entities;
using Volo.Abp.EntityFrameworkCore;

namespace ApplicationFrame.EntityFrameworkCore
{
    /// <summary>
    /// BaseDbContext
    /// </summary>
    /// <typeparam name="TDbContext">具体实现的DbContext</typeparam>
    /// <typeparam name="TEntityClass">任意一个实体类型，用于动态添加实体和加载实体配置，同一个程序集</typeparam>
    public abstract class BaseDbContext<TDbContext> : AbpDbContext<TDbContext> where TDbContext : BaseDbContext<TDbContext>
    {
        /// <summary>
        /// ctor
        /// </summary>
        public BaseDbContext(DbContextOptions<TDbContext> options) : base(options)
        {
        }

        /// <summary>
        /// OnModelCreating
        /// </summary>
        /// <param name="modelBuilder">ModelBuilder</param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            AddEntitiesToModle(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(TDbContext).Assembly);
            foreach (var item in modelBuilder.Model.GetEntityTypes())
            {
                foreach (var p in item.GetProperties())
                {
                    if (p.ClrType == typeof(DateTimeOffset?))
                        p.SetValueConverter(new NullDateTimeOffsetValueConverter());
                    else if (p.ClrType == typeof(DateTimeOffset))
                        p.SetValueConverter(new DateTimeOffsetValueConverter());
                    else if (p.ClrType == typeof(DateTime?))
                        p.SetValueConverter(new DateTimeValueConverter());
                    else if (p.ClrType == typeof(DateTime?))
                        p.SetValueConverter(new NullDateTimeValueConverter());
                }
            }
        }
        #region private method
        private void AddEntitiesToModle(ModelBuilder modelBuilder)
        {
            var types = typeof(TDbContext).Assembly.GetTypes()
                .Where(m => m.IsClass && m.IsPublic && !m.IsAbstract && !m.IsGenericType && !m.IsInterface && m.IsAssignableTo(typeof(IEntity)));
            var olds = modelBuilder.Model.GetEntityTypes().ToArray();
            foreach (var type in types)
            {
                if (olds.Count(m => m.ClrType == type) == 0)
                    modelBuilder.Model.AddEntityType(type);
            }
        }
        #endregion
    }

    class NullDateTimeOffsetValueConverter : ValueConverter<DateTimeOffset?, DateTimeOffset?>
    {
        public NullDateTimeOffsetValueConverter()
            : base(m => m.HasValue ? TimeZoneInfo.ConvertTimeFromUtc(m.Value.ToUniversalTime().DateTime, TimeZoneInfo.Local) : m,
                  m => m.HasValue ? TimeZoneInfo.ConvertTimeFromUtc(m.Value.ToUniversalTime().DateTime, TimeZoneInfo.Local) : m,
                  null)
        { }
    }

    class DateTimeOffsetValueConverter : ValueConverter<DateTimeOffset, DateTimeOffset>
    {
        public DateTimeOffsetValueConverter()
            : base(m => TimeZoneInfo.ConvertTimeFromUtc(m.ToUniversalTime().DateTime, TimeZoneInfo.Local),
                  m => TimeZoneInfo.ConvertTimeFromUtc(m.ToUniversalTime().DateTime, TimeZoneInfo.Local),
                  null)
        { }
    }

    class DateTimeValueConverter : ValueConverter<DateTime, DateTime>
    {
        public DateTimeValueConverter()
            : base(m => TimeZoneInfo.ConvertTimeFromUtc(m.ToUniversalTime(), TimeZoneInfo.Local),
                  m => TimeZoneInfo.ConvertTimeFromUtc(m.ToUniversalTime(), TimeZoneInfo.Local),
                  null)
        { }
    }

    class NullDateTimeValueConverter : ValueConverter<DateTime?, DateTime?>
    {
        public NullDateTimeValueConverter()
            : base(m => m.HasValue ? TimeZoneInfo.ConvertTimeFromUtc(m.Value.ToUniversalTime(), TimeZoneInfo.Local) : m,
                  m => m.HasValue ? TimeZoneInfo.ConvertTimeFromUtc(m.Value.ToUniversalTime(), TimeZoneInfo.Local) : m,
                  null)
        { }
    }
}
